package mmc.resource.models.collada;

import java.math.BigInteger;
import java.util.List;

import org.collada.x2005.x11.colladaSchema.InputLocalOffset;
import org.collada.x2005.x11.colladaSchema.MeshDocument.Mesh;
import org.collada.x2005.x11.colladaSchema.SourceDocument.Source;

public class ColladaFloatDataSource{
	int indexStride=1, offset=0;
	int dataStride=1;
	float[] data;
	List<BigInteger> index;
	
	public ColladaFloatDataSource(Mesh mesh, InputLocalOffset in, List<BigInteger> index) {
		Source s = resolveSource(mesh,in.getSource());
		String[] sin = s.getFloatArray1().getStringValue().split("\\ ");
		data = new float[sin.length];
		this.index = index;
		offset = in.getOffset().intValue();
		dataStride = s.getTechniqueCommon().getAccessor().getStride().intValue();
		
		for(int i=0;i<sin.length;i++){
			data[i] = Float.parseFloat(sin[i]);
		}
	}
	
	public float get(int i,int xyzOffset){
		return data[index.get(i*indexStride+offset).intValue()*dataStride+xyzOffset];
	}
	
	private static Source resolveSource(Mesh mesh, String sourceUrl){
		assert sourceUrl.charAt(0) == '#';
		sourceUrl = sourceUrl.substring(1);
		
		for(Source s : mesh.getSourceArray()){
			if(s.getId().equals(sourceUrl))
				return s;
		}
		
		if(mesh.getVertices().getId().equals(sourceUrl)){
			return resolveSource(mesh, mesh.getVertices().getInputArray()[0].getSource());
		}
		
		throw new RuntimeException("Invalid sourceUrl: "+sourceUrl);
	}
}